/**
 * @param {number[]} heights
 * @return {number}
 */
var largestRectangleArea = function (heights) {
  if (!heights || heights.length === 0) return 0

  //最大面积
  let maxArea = 0
  //单调栈
  let stack = []
  //首位添加两个哨兵
  heights = [0, ...heights, 0]

  for (let i = 0; i < heights.length; i++) {
    while (stack.length > 0 && heights[i] < heights[stack[stack.length - 1]]) {
      let height = heights[stack.pop()]
      let width = i - stack[stack.length - 1] - 1
      maxArea = Math.max(maxArea, height * width)
    }
    stack.push(i)
  }

  //返回结果
  return maxArea
};

console.log(largestRectangleArea([2, 1, 5, 6, 2, 3]))